<template>
  <div class="add-eidt">
    <c-section title="门店建设基本信息">
      <c-list ref="form" :column="3" :model="formData" :rules="formRules" label-width="120px">
        <c-list-item label="门店编码" required>
          <el-input v-model="formData.shopCode" type="text" disabled />
        </c-list-item>
        <c-list-item label="门店" prop="shopCode">
          <c-single-dialog
            ref="shopCode"
            v-model="formData.shopCode"
            :label.sync="formData.shopName"
            :props="{label:'shopName',value:'shopCode'}"
            :disabled="disabled"
            :config="{
              title:'门店',
              width:'600px',
              interfacePath:'/slm-admin/api/v1/shopConstruct/shop/page',
              method:'post',
              filtersRaw:shopFiltersRaw,
              paramsRaw:{},
              setting:[
                {prop:'shopCode',title:'编码',width:80},
                {prop:'shopName',title:'名称',width:200}
              ]
            }"
            @change="shopDialogChangeHandle"
          />
        </c-list-item>
        <c-list-item label="所属客户编码" prop="clientCode">
          <el-input v-model="formData.clientCode" type="text" disabled />
        </c-list-item>
        <c-list-item label="所属客户" prop="clientName">
          <el-input v-model="formData.clientName" type="text" disabled />
        </c-list-item>
        <c-list-item label="所属办事处" prop="officeName">
          <el-input v-model="formData.officeName" type="text" disabled />
        </c-list-item>
        <c-list-item label="办事处性质" prop="officeNature">
          <el-input v-model="formData.officeNature" type="text" disabled />
        </c-list-item>
        <c-list-item label="门店类型" prop="shopType">
          <c-dict-select v-model="formData.shopType" dict-type-code="SHOP_TYPE" disabled />
        </c-list-item>
        <c-list-item label="门店业务类型" prop="shopBizType">
          <c-dict-select v-model="formData.shopBizType" multiple dict-type-code="BIZ_TYPE" disabled />
        </c-list-item>
        <c-list-item label="门店城市级别" prop="shopCityLevel">
          <c-dict-select v-model="formData.shopCityLevel" dict-type-code="CITY_LEVEL" disabled />
        </c-list-item>
        <c-list-item label="门店详细地址" prop="shopAddress" :span="3">
          <el-input v-model="formData.shopAddress" type="text" disabled />
        </c-list-item>
        <c-list-item label="门店建设项目号" prop="constCode">
          <c-single-dialog
            ref="constCode"
            v-model="formData.constCode"
            :props="{label:'constCode',value:'constCode'}"
            :focus-query="true"
            :multiple="false"
            :disabled="!formData.shopCode || disabled"
            :config="{
              title:'门店建设项目号',
              width:'600px',
              interfacePath:'/slm-admin/api/v1/shopConstruct/page',
              method:'post',
              paramField:'constCode',
              filtersRaw:constCodeFiltersRaw,
              paramsRaw:{},
              setting:[
                {prop:'constCode',title:'门店建设项目号',width:120},
                {prop:'shopName',title:'门店'},
              ]
            }"
            @change="constCodeChangeHandle"
          />
        </c-list-item>
        <c-list-item label="门店营业状态" prop="businessStatus">
          <c-dict-select v-model="formData.businessStatus" disabled dict-type-code="SHOP_BIZ_STATE" />
        </c-list-item>
        <c-list-item label="报图类型" prop="marketType">
          <c-dict-select v-model="formData.marketType" disabled dict-type-code="MARKET_TYPE" />
        </c-list-item>
        <c-list-item label="门店建设类型" prop="constType">
          <c-dict-select v-model="formData.constType" disabled dict-type-code="CONST_TYPE" />
        </c-list-item>
        <c-list-item label="商家类别" prop="bizmanType">
          <c-dict-select v-model="formData.bizmanType" disabled dict-type-code="BIZMAN_TYPE" />
        </c-list-item>
        <c-list-item label="装修形式" prop="decorationForm">
          <c-dict-select v-model="formData.decorationForm" multiple disabled dict-type-code="DECORATION_FORM" />
        </c-list-item>
        <c-list-item label="门店建设范围" prop="decorationRange">
          <c-dict-checkbox-select v-model="formData.decorationRange" disabled dict-type-code="DECORATION_RANGE" @change="changeDRHandle" />
        </c-list-item>
        <c-list-item label="设计申请面积" suffix="㎡" :value="designInfo.shopTotalArea || 0" />
        <c-list-item label="设计申请时间" :value="designInfo.reportApplyTime" />
      </c-list>
    </c-section>
    <c-section title="装修申请信息">

      <c-list ref="formApply" :column="3" :model="formData" :rules="formRules" label-width="140px">
        <c-list-item label="本次装修范围" prop="range">
          <c-dict-checkbox-select v-model="formData.range" :includes="range" :disabled="formData.decorationRange.length===0" dict-type-code="DECORATION_RANGE" @change="changeRHandle" />
        </c-list-item>
        <c-list-item label="装修性质" prop="nature">
          <c-dict-select v-model="formData.nature" :exclude="(formData.range&&!formData.range.includes('STORES'))?'PUBLICS':''" dict-type-code="DECORATION_NATURE" />
        </c-list-item>
        <template v-if="showEarnest">
          <c-list-item label="是否扣除保证金" prop="isDeductCashDeposit">
            <c-dict-select v-model="formData.isDeductCashDeposit" dict-type-code="BOOLEANS" />
          </c-list-item>
          <c-list-item v-show="['1', 1].includes(formData.isDeductCashDeposit)" label="(整改)保证金扣款金额" prop="deductCashDepositAmount">
            <c-input-number v-model="formData.deductCashDepositAmount" float />
          </c-list-item>
        </template>

      </c-list>
    </c-section>
    <c-section title="色板需求信息">
      <template #title>
        <span style="color:#F56C6C;font-size:12px;margin-left:5px">注：色板、工法展板需求由定制客户经理核实。</span>
      </template>
      <c-list ref="form" :column="2" :model="formData" :rules="formRules" label-width="140px">
        <c-list-item label="是否需要新店色板包" prop="isNewShopColor">
          <el-select
            v-model="formData.isNewShopColor"
            clearable
            filterable
          >
            <el-option :value="1" label="是" />
            <el-option :value="0" label="否" />
          </el-select>
        </c-list-item>
        <template v-if="formData.isNewShopColor==1">
          <c-list-item :rules="[{ required: !!formData.isNewShopColor, message: '请选择', trigger: 'change' }]" label="需求色板类型" prop="colorType">
            <c-dict-select v-model="formData.colorType" multiple dict-type-code="SWATCHES_TYPE" />
          </c-list-item>
          <c-list-item :rules="[{ required: !!formData.isNewShopColor, message: '请选择', trigger: 'change' }]" label="需求明细" prop="colorDefiniteDetailed">
            <c-dict-select v-model="formData.colorDefiniteDetailed" multiple dict-type-code="SWATCHES_DETAIL" />
          </c-list-item>
        </template>
        <c-list-item label="是否需要工法展板" prop="isDisplayBoard">
          <el-select
            v-model="formData.isDisplayBoard"
            clearable
            filterable
          >
            <el-option :value="1" label="是" />
            <el-option :value="0" label="否" />
          </el-select>

          <!--  <template v-if="formData.isNewShopColor==1&&formData.isDisplayBoard==1">   -->
        </c-list-item>
        <template v-if="formData.isDisplayBoard==1">
          <c-list-item :rules="[{ required: !!formData.isDisplayBoard, message: '请选择', trigger: 'change' }]" label="需求内框尺寸" prop="innerSize">
            <c-dict-select v-model="formData.innerSize" multiple dict-type-code="SWATCHES_SIZE" />
          </c-list-item>
        </template>
      </c-list>
    </c-section>
    <c-section title="窗帘需求信息">
      <c-list ref="form" :column="2" :model="formData" :rules="formRules" label-width="130px">
        <c-list-item label="是否需要窗帘物料" prop="isCurtain">
          <el-select v-model="formData.isCurtain" @change="changeCurtainValue">
            <el-option :value="1" label="是" />
            <el-option :value="0" label="否" />
          </el-select>
        </c-list-item>
        <c-list-item
          v-show="formData.isCurtain"
          :rules="[{ required: !!formData.isCurtain, message: '请选择'}]"
          label="窗帘展示内框尺寸"
          prop="curtainSize"
        >
          <c-dict-select
            v-model="formData.curtainSize"
            dict-type-code="CURTAIN_SIZE"
          />
        </c-list-item>
        <c-list-item
          v-show="formData.isCurtain"
          :rules="[{ required: !!formData.isCurtain, message: '请选择' }]"
          label="窗帘样本6QR20078001"
          prop="curtainSamples"
        >
          <el-select v-model="formData.curtainSamples">
            <el-option :value="1" label="是" />
            <el-option :value="0" label="否" />
          </el-select>
        </c-list-item>
        <c-list-item
          v-show="formData.isCurtain"
          :rules="[{ required: !!formData.isCurtain, message: '请选择' }]"
          label="轨道五金包6QR20077001"
          prop="railHardware"
        >
          <el-select v-model="formData.railHardware">
            <el-option :value="1" label="是" />
            <el-option :value="0" label="否" />
          </el-select>
        </c-list-item>
      </c-list>

    </c-section>
    <c-section v-if="showStartCondition" title="现场开工条件判断">
      <c-list ref="formCondition" :column="1" :model="formData" :rules="formRules" label-width="120px">
        <!-- <c-list-item class="err-offset" prop="constPicRemark">
          <c-checkbox-remark v-model="formData.startCondition.constPicRemark" :remark.sync="formData.constPicRemark" label="施工图纸确定" remark-label="施工图纸备注" label-width="200px" remark-label-width="100px" />
        </c-list-item> -->
        <c-list-item class="err-offset" prop="acRemark">
          <c-checkbox-remark v-model="formData.startCondition.acRemark" :remark.sync="formData.acRemark" label="空调符合装修标准" remark-label="空调备注" label-width="200px" remark-label-width="100px" />
        </c-list-item>
        <c-list-item class="err-offset" prop="wpRemark">
          <c-checkbox-remark v-model="formData.startCondition.wpRemark" :remark.sync="formData.wpRemark" label="防水符合装修标准" remark-label="防水备注" label-width="200px" remark-label-width="100px" />
        </c-list-item>
        <c-list-item class="err-offset" prop="fcRemark">
          <c-checkbox-remark v-model="formData.startCondition.fcRemark" :remark.sync="formData.fcRemark" label="消防符合装修标准" remark-label="消防备注" label-width="200px" remark-label-width="100px" />
        </c-list-item>
        <c-list-item class="err-offset" prop="horizonRemark">
          <c-checkbox-remark v-model="formData.startCondition.horizonRemark" :remark.sync="formData.horizonRemark" label="地平已找平" remark-label="地平备注" label-width="200px" remark-label-width="100px" />
        </c-list-item>
      </c-list>
    </c-section>
    <c-section style="padding-bottom:50px">
      <c-list ref="formTime" :column="1" :model="formData" :rules="formRules" label-width="125px">
        <c-list-item label="预计进场装修时间" prop="expectDecorationTime" :span="0.5">
          <el-date-picker
            v-model="formData.expectDecorationTime"
            type="date"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择日期"
            clearable
          />
        </c-list-item>
        <c-list-item label="预计开业时间" prop="expectOpenTime" :span="0.5">
          <el-date-picker
            v-model="formData.expectOpenTime"
            type="date"
            format="yyyy-MM-dd"
            placeholder="选择日期"
            value-format="yyyy-MM-dd HH:mm:ss"
            clearable
          />
        </c-list-item>
        <c-list-item label="申请说明" prop="expectDesc">
          <el-input v-model="formData.expectDesc" type="textarea" :autosize="{minRows: 3}" placeholder="申请说明" maxlength="1024" show-word-limit clearable />
        </c-list-item>
      </c-list>
    </c-section>

    <div class="footer-btn">
      <c-button type="primary" @click="cancelHandle">取消</c-button>
      <c-button type="primary" @click="clickSaveHandle">保存</c-button>
      <c-button type="primary" @click="clickNextStep">下一步</c-button>
    </div>
  </div>
</template>
<script>
import { deepClone, otherFiltersItem } from '@/utils'
import { postAddOrEdit, getShopDesignInfo } from '@/api/decorate'
import CInputNumber from '@/components/CInputNumber'
export default {
  name: 'DecorateAddEdit',
  components: {
    CInputNumber
  },
  props: {
    formData: {
      type: Object,
      default: () => ({}),
      required: true
    }
  },
  data() {
    // 验证预计装修进场时间
    const validatorEDT = (r, v, c) => {
      const { expectDecorationTime, expectOpenTime } = this.formData
      if (expectDecorationTime && expectOpenTime) {
        const edt = new Date(expectDecorationTime).getTime()
        const eot = new Date(expectOpenTime).getTime()
        if (edt > eot) {
          c(new Error('预计进场装修时间不能大于预计开业时间'))
        } else {
          c()
        }
        return
      }
      c()
    }
    const validatorConst = key => {
      return (r, v, c) => {
        if (!this.formData.startCondition[key] && (v === '' || v === undefined)) {
          c(new Error('请输入备注'))
        } else {
          c()
        }
      }
    }
    // 验证是否需要扣除保证金
    const validatorIDCD = (r, v, c) => {
      if (this.showEarnest && (v === undefined || v === null || v === '')) {
        c(new Error('请选择是否扣除保证金'))
      } else {
        c()
      }
    }
    const validatorDCDA = (r, v, c) => {
      const t = v === undefined || v === null || v === '' ? 0 : Number(v)
      if (this.showEarnest && ['1', 1].includes(this.formData.isDeductCashDeposit) && t <= 0) {
        c(new Error('请输入保证金扣款金额'))
      } else {
        c()
      }
    }
    return {
      shopFiltersRaw: [
        // otherFiltersItem('isEnd', '0', '=')
        // otherFiltersItem('constSchedule', 'I', '=')
      ], // 门店
      constCodeFiltersRaw: [],
      range: [], // 本次装修范围可选
      formRules: {
        shopCode: [{ required: true, message: '请选择门店', trigger: 'change' }],
        constCode: [{ required: true, message: '请选择门店建设项目号', trigger: 'change' }],
        range: [{ required: true, message: '请优先选择门店建设项目号', trigger: 'change' }],
        nature: [{ required: true, message: '请选择装修性质', trigger: 'change' }],
        isDeductCashDeposit: [{ required: true, validator: validatorIDCD, trigger: 'change' }],
        isCurtain: [{ required: true, message: '请选择', trigger: 'change' }],
        deductCashDepositAmount: [{ required: true, validator: validatorDCDA, trigger: 'change' }],
        expectDecorationTime: [
          { required: true, message: '请预计进场装修时间', trigger: 'change' },
          { required: true, validator: validatorEDT, trigger: 'change' }
        ],
        expectOpenTime: [
          { required: true, message: '请选择预计开业时间', trigger: 'change' },
          { required: true, validator: validatorEDT, trigger: 'change' }
        ],
        expectDesc: [{ required: true, message: '请填写申请说明', trigger: 'change' }],
        // 条件
        constPicRemark: [{ required: false, validator: validatorConst('constPicRemark'), trigger: 'blur' }],
        acRemark: [{ required: true, validator: validatorConst('acRemark'), trigger: 'blur' }],
        wpRemark: [{ required: true, validator: validatorConst('wpRemark'), trigger: 'blur' }],
        fcRemark: [{ required: true, validator: validatorConst('fcRemark'), trigger: 'blur' }],
        horizonRemark: [{ required: true, validator: validatorConst('horizonRemark'), trigger: 'blur' }],
        isNewShopColor: [{ required: true, message: '是否需要新店色板包', trigger: 'change' }],
        isDisplayBoard: [{ required: true, message: '是否需要工法展板', trigger: 'change' }]

      },
      designInfo: {} // 设计信息
    }
  },
  computed: {
    showStartCondition() {
      return this.formData.range && this.formData.range.includes('STORES')
    },
    disabled() {
      return this.formData.dataFrom === 'SLM'
    },
    showEarnest() {
      return this.showStartCondition && this.formData.nature === 'PRIVATES'
    }
  },
  watch: {
    formData: {
      handler(v) {
        this.range = v.decorationRange || []
      }
    },
    showEarnest: {
      handler(v) {
        if (!v) {
          this.$set(this.formData, 'isDeductCashDeposit', '')
          this.$set(this.formData, 'deductCashDepositAmount', '')
        }
      }
    },
    'formData.isDeductCashDeposit': {
      handler(v) {
        if (v !== '1' && v !== 1) {
          this.$set(this.formData, 'deductCashDepositAmount', '')
        }
      }
    }
  },
  created() {
    console.log(this.formData, '114')
    // 验证formData.startCondition
    for (const k of Object.keys(this.formData.startCondition || {})) {
      this.$watch(`formData.startCondition.${k}`, (n, o) => {
        this.$nextTick(() => {
          this.$refs.formCondition.validateField([k])
        })
      })
    }
    if (this.$route.query.constCode) {
      this.getDesignInfo(this.$route.query.constCode)
    }
  },
  methods: {
    changeCurtainValue(data) {
      console.log(data)
      this.formData.curtainSize = ''
      this.$set(this.formData, 'curtainSamples', undefined)
      this.$set(this.formData, 'railHardware', undefined)
    },
    // 设置类型数据
    constCodeChangeHandle(data, clear) {
      this.getDesignInfo(data.constCode)
      const keys = this.$split('marketType constCode constType bizmanType decorationForm decorationRange businessStatus officeNature', ' ')
      if (clear) {
        for (const key of keys) {
          let v = ''
          if (key === 'decorationRange') {
            v = []
            this.range = []
            this.changeDRHandle(this.range)
          }
          this.$set(this.formData, key, v)
        }
        return
      }
      const arrKeys = this.$split('decorationForm')
      for (const key of keys) {
        let v = data[key]
        if (key === 'decorationRange') {
          v = this.$split(v)
          this.range = deepClone(v)
          this.changeDRHandle(this.range)
        } else if (arrKeys.includes(key)) {
          v = this.$split(v)
        }
        this.$set(this.formData, key, v || '')
      }
    },
    // 获取设计信息
    getDesignInfo(constCode) {
      if (!constCode) {
        this.designInfo = {}
        return
      }
      getShopDesignInfo(constCode).then(res => {
        this.designInfo = res.data || {}
      })
    },
    // 门店变化
    shopDialogChangeHandle(data) {
      this.constCodeChangeHandle(data, true)
      // 建设项目号查询条件
      this.constCodeFiltersRaw = [
        otherFiltersItem('shopCode', data.shopCode, '='),
        otherFiltersItem('isEnd', '0', '=')
        // otherFiltersItem('constSchedule', 'I', '=')
      ]
      const keys = this.$split('clientCode clientName officeCode officeName shopType shopBizType shopBizTypeName shopCityLevel shopAddress', ' ')
      const arrKeys = this.$split('shopBizType')
      for (const key of keys) {
        let v = data[key]
        if (arrKeys.includes(key)) {
          v = this.$split(v)
        }
        this.$set(this.formData, key, v || '')
      }
      this.designInfo = {}
    },
    // 装修范围改变
    changeDRHandle(v) {
      this.range = v
      this.formData.range = deepClone(v)
    },
    // 本次装修范围改变
    changeRHandle(v) {
      if (v && !v.includes('STORES') && v.includes('DOOR')) {
        this.$set(this.formData, 'nature', 'PRIVATES')
      }
      if (!v || v.length <= 0) {
        this.$set(this.formData, 'nature', '')
      }
      // if (v.length > 1) {
      //   this.$set(this.formData, 'range', [v.pop()])
      // }
    },
    // 校验
    validate() {
      const t = [this.$refs.form.validate(), this.$refs.formApply.validate(), this.$refs.formTime.validate()]
      if (this.showStartCondition) {
        t.push(this.$refs.formCondition.validate())
      }
      return Promise.all(t)
    },
    saveHandle() {
      return this.validate().then(() => {
        if (this.formData.businessStatus === '' || this.formData.businessStatus === undefined || [3, 4, 5, '3', '4', '5'].includes(this.formData.businessStatus)) {
          this.$message.warning('当前门店营业状态异常，无法提报装修申请')
          return Promise.reject('')
        }
        const data = this.handleData(deepClone(this.formData))
        // schedule
        return postAddOrEdit(data).then(res => {
          this.$message.success('保存成功！')
          return res
        })
      })
    },
    clickSaveHandle() {
      return this.saveHandle().then(res => {
        this.$store.dispatch('views/goFirst')
      })
    },
    handleData(data) {
      const checks = Object.entries(data.startCondition || {})
      const startCondition = []
      for (const [k, v] of checks) {
        if (!data.range && data.range.includes('STORES')) {
          data[k] = ''
        }
        if (v) {
          startCondition.push(k)
        }
      }
      data.startCondition = startCondition.join(',')
      // 范围
      data.decorationRange = (data.decorationRange || []).join(',')
      data.range = (data.range || []).join(',')
      data.shopBizType = (data.shopBizType || []).join(',')
      data.decorationForm = (data.decorationForm || []).join(',')
      data.colorType = (data.colorType || []).join(',')
      data.colorDefiniteDetailed = (data.colorDefiniteDetailed || []).join(',')
      data.innerSize = (data.innerSize || []).join(',')
      // 处理input-width-dialog
      delete data.constCodeDialog
      return data
    },
    clickNextStep() {
      return this.saveHandle().then(res => {
        this.formData.id = res.msg
        this.$emit('get-drawing-data', res.msg)
        this.$emit('next', 1)
      })
    },
    cancelHandle() {
      this.$msgbox({
        title: '取消',
        message: '当放弃当前操作，退出装修列表，是否确认？',
        type: 'warning',
        showCancelButton: true
      }).then(() => {
        this.$store.dispatch('views/goFirst')
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.add-eidt{

}
.err-offset{
  /deep/ .el-form-item__error{
    margin-left: 310PX;
  }
}
</style>
